//
//  BLEManager.m
//  BLETest
//
//  Created by Latchesar Ionkov on 3/12/13.
//  Copyright (c) 2013 Alex Ionkov and Ethan Aulwes. All rights reserved.
//

#import "BLEManager.h"

@implementation BLEManager

- (void) start
{
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
//    for(int i = 0; i < 10; i++)
//        rssi[i] = 0;
    [self startScan];
}

- (void) startScan
{
    NSLog(@"startScan");
    
    manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    devs = [[NSMutableDictionary alloc] init];
    
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
    [manager scanForPeripheralsWithServices:nil options:options];
}

/*
 Request CBCentralManager to stop scanning for heart rate peripherals
 */
- (void) stopScan
{
    NSLog(@"stopScan");
    [manager stopScan];
}


- (void) dealloc
{
    [self stopScan];
//    [manager release];
//    [super dealloc];
}

#pragma mark - CBCentralManager delegate methods
/*
 Invoked whenever the central manager's state is updated.
 */
- (void) centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"DidUpdateState");
}

/*
 Invoked when the central discovers heart rate peripheral while scanning.
 */
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)aPeripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSNumber *r;
     Device *dev = [devs objectForKey:aPeripheral.name];
    
    if (!dev) {
//        NSLog(@"Device %@ not found", aPeripheral.name);
        dev = [[Device alloc] init];
        dev->name = aPeripheral.name;
        dev->rssiHistory = [[NSMutableArray alloc] init];
        dev->lock = false;
        [devs setObject:dev forKey:aPeripheral.name];
    }

    NSMutableArray *rssi = dev->rssiHistory;
    
    [rssi addObject:RSSI];
    if (rssi.count > 10)
        [rssi removeObjectAtIndex:0];

    double val = 0;
    for(r in rssi) {
        val += r.intValue;
    }
    val = val/rssi.count;
    dev->rssi = val;
    
    for(NSString *devname in devs) {
        Device *dev = [devs objectForKey:devname];
        printf("%s:%03d ", dev->name.lossyCString, dev->rssi);
        if (dev->rssi < -80 && !dev->lock){
            dev->lock = TRUE;
            system("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend");
        }
    }
    printf("\n");
}

/*
 Invoked when the central manager retrieves the list of known peripherals.
 Automatically connect to first known peripheral
 */
- (void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals
{
    NSLog(@"didRetrievePeripherals");
}

/*
 Invoked whenever a connection is succesfully created with the peripheral.
 Discover available services on the peripheral
 */
- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)aPeripheral
{
    NSLog(@"didConnectPeripheral");
}

/*
 Invoked whenever an existing connection with the peripheral is torn down.
 Reset local variables
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)aPeripheral error:(NSError *)error
{
    NSLog(@"didDisconnectPeripheral");
}

/*
 Invoked whenever the central manager fails to create a connection with the peripheral.
 */
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)aPeripheral error:(NSError *)error
{
    NSLog(@"Fail to connect to peripheral: %@ with error = %@", aPeripheral, [error localizedDescription]);
}

@end

@implementation Device
@end
